<!--  -->
<template>
  <div class="login-bg">
    <div class="login-panel">
      <h2 class="login-title">系统登录</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="login-form">
        <el-form-item label="账户/手机号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账户名或手机号" clearable maxlength="32" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password maxlength="32" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div style="display: flex; align-items: center;">
            <el-input v-model="form.code" placeholder="请输入验证码" maxlength="6" style="width: 160px;" />
            <img :src="codeUrl" @click="getCode" class="code-img" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :loading="loading">登录</el-button>
          <el-button style="margin-left:12px" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { inject, ref,onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import qs from 'qs'

const router = useRouter()
const formRef = ref()
const loading = ref(false)
const codeUrl = ref('')

const form = ref({
  username: '',
  password: '',
  role: "admin",
  code: '',    // 用户输入的验证码
  uuid: ''   // 后端生成的uuid
})

const rules = {
  username: [
    { required: true, message: '请输入账户名或手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const axios = inject('axios');

const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    loading.value = true


    try {
      const res = await axios.post('/user/login', qs.stringify(form.value))
      const result = res.data
      loading.value = false
      if (result.status == 200) {
        localStorage.setItem('userRole', "admin")
        localStorage.setItem('username', result.data.user.username)
        localStorage.setItem('userId', result.data.user.userId)
        let token = 'admin'
        sessionStorage.setItem('token', token);
        sessionStorage.setItem('isLogin', true)
        router.replace('/HomeView')
      } else {
        ElMessage.error(result.msg || '登录失败')
        getCode()
        form.value.code = '' // 清空用户输入的验证
      }
    } catch (e) {
      loading.value = false
      ElMessage.error('网络异常')
      getCode()
    }
  })
}


const onReset = () => {
  formRef.value.resetFields()
}

const getCode = async () => {
  try {
    const res = await axios.get('/captcha/getCode')
    if (res.data.code === 200 || res.data.status === 200) {
      form.value.uuid = res.data.data.uuid
      codeUrl.value = 'data:image/gif;base64,' + res.data.data.img
    }
  } catch (err) {
    ElMessage.error('验证码获取失败')
  }
}

onMounted(() => {
  getCode()
})
</script>


<style scoped>
.login-bg {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(90deg, #fffbe6 60%, #ffe0b2 100%);
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.login-panel {
  width: 370px;
  min-height: 200px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(252, 211, 149, .25);
  margin-right: 12vw;
  padding: 44px 38px 24px 38px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  animation: fadeIn .5s;
}

.login-title {
  font-size: 28px;
  font-weight: bold;
  color: #faad14;
  text-align: center;
  margin-bottom: 22px;
  letter-spacing: 2px;
}

.login-form :deep(.el-form-item__label) {
  font-size: 17px;
  color: #666;
  font-weight: 500;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 8px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateX(80px);
  }

  to {
    opacity: 1;
    transform: none;
  }
}

.code-img {
  height: 38px;
  margin-left: 12px;
  cursor: pointer;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>
